"""
@File    :   router.py
@Time    :   2024/03/11 13:51:48
@Author  :   Qrj
@Email   :   923207736@qq.com
@description   :   OAuth2授权码模式认证相关路由
"""

from typing import Annotated

from fastapi import APIRouter, Depends, Request, status
from fastapi.responses import HTMLResponse, RedirectResponse

from src.business.admin.system.oauth2.auth.authorization_code.dependencies.route_depend import (
    RouteDependGetCodeLoginPage,
    route_depend_authorization_code_create_double_token,
    route_depend_get_code_login_page,
    route_depened_create_authorization_code,
)
from src.business.admin.system.oauth2.auth.authorization_code.schemas.out import (
    AuthorizationCodeCompleteOutSchema,
)
from src.business.admin.system.oauth2.auth.captcha.dependencies.no_introduction import (
    depend_validate_and_del_image_captcha,
    depend_validate_and_del_sliding_captcha,
)
from src.business.admin.system.oauth2.auth.captcha.enums import CaptchaTypeEnum
from src.business.admin.system.oauth2.token.schemas.out import (
    DoubleTokenCompleteOutSchema,
)
from src.config import get_app_settings
from src.utils.jinja2 import render_async_template
from src.utils.unified_response import SuccessApiJSONResponse

# 创建路由
router = APIRouter(
    prefix="/admin/system/oauth2/auth/authorization-code",
    tags=[
        "后台OAuth2授权码模式认证接口",
    ],
)


@router.get("/code-login-page", summary="获取授权码的用户登录页面")
async def route_get_code_login_page(
    code_login_page_info: Annotated[
        RouteDependGetCodeLoginPage,
        Depends(route_depend_get_code_login_page),
    ],
    request: Request,
):
    context = {
        "request": request,
        "tenant": code_login_page_info.tenant,
        "oauth2_client": code_login_page_info.oauth2_client,
        "redirect_uri": code_login_page_info.redirect_uri,
        "state": code_login_page_info.state,
    }
    login_page_html = await render_async_template(
        "business/system/oauth2/authorization_code/get_code_login_page.html",
        context=context,
    )
    return HTMLResponse(content=login_page_html)


# 获取应用配置
settings = get_app_settings()

# 根据是否开启验证码来解锁对应的路由
if (
    settings.enable_user_login_captcha
    and settings.user_login_captcha_type == CaptchaTypeEnum.image
):
    # 使用图像验证码
    @router.post(
        "/code-redirect",
        summary="授权码用户登录并重定向到用户提供的redirect_uri(需要图像验证码)",
    )
    async def route_code_login_and_redirect_uri(
        image_captcha_validate_result: Annotated[
            bool, Depends(depend_validate_and_del_image_captcha)
        ],
        code_info: Annotated[
            AuthorizationCodeCompleteOutSchema,
            Depends(route_depened_create_authorization_code),
        ],
    ):
        # 对方会在重定向uri中构建请求获取数据, 并使用获取到的数据进行逻辑判断(已有用户或新增用户跳转)
        return RedirectResponse(
            code_info.include_query_redirect_uri, status_code=status.HTTP_302_FOUND
        )
elif (
    settings.enable_user_login_captcha
    and settings.user_login_captcha_type == CaptchaTypeEnum.sliding_puzzle
):
    # 使用滑块验证码
    @router.post(
        "/code-redirect",
        summary="授权码用户登录并重定向到用户提供的redirect_uri(需要滑块验证码)",
    )
    async def route_code_login_and_redirect_uri(
        sliding_captcha_validate_result: Annotated[
            bool, Depends(depend_validate_and_del_sliding_captcha)
        ],
        code_info: Annotated[
            AuthorizationCodeCompleteOutSchema,
            Depends(route_depened_create_authorization_code),
        ],
    ):
        # 对方会在重定向uri中构建请求获取数据, 并使用获取到的数据进行逻辑判断(已有用户或新增用户跳转)
        return RedirectResponse(
            code_info.include_query_redirect_uri, status_code=status.HTTP_302_FOUND
        )
else:
    # 不使用验证码
    @router.post(
        "/code-redirect", summary="授权码用户登录并重定向到用户提供的redirect_uri"
    )
    async def route_code_login_and_redirect_uri(
        code_info: Annotated[
            AuthorizationCodeCompleteOutSchema,
            Depends(route_depened_create_authorization_code),
        ],
    ):
        # 对方会在重定向uri中构建请求获取数据, 并使用获取到的数据进行逻辑判断(已有用户或新增用户跳转)
        return RedirectResponse(
            code_info.include_query_redirect_uri, status_code=status.HTTP_302_FOUND
        )


@router.post("/authiruze", summary="请求认证")
async def route_authiruze(
    double_token: Annotated[
        DoubleTokenCompleteOutSchema,
        Depends(route_depend_authorization_code_create_double_token),
    ],
):
    access_token, refresh_token = double_token.access_token, double_token.refresh_token
    data = {
        "access_token": access_token.access_token,
        "access_token_expiration_datetime": access_token.expiration_datetime,
        "refresh_token": refresh_token.refresh_token,
        "refresh_token_expiration_datetime": refresh_token.expiration_datetime,
        "token_type": access_token.token_type,
        "scopes": access_token.oauth2_scopes,
    }
    return SuccessApiJSONResponse(message="OAuth2授权码模式请求认证成功", data=data)
